#include "common.h"

STRING timeStr(){
	return timeStr(time(NULL));
}

STRING timeStr(time_t t){
	tm *ltm = localtime(&t);
	char year[4], month[2], day[2], hour[2], minute[2], second[2];
	sprintf(year, "%d", 1900 + ltm->tm_year);
	sprintf(month, "%02d", 1 + ltm->tm_mon);
	sprintf(day, "%02d", ltm->tm_mday);
	sprintf(hour, "%02d", ltm->tm_hour);
	sprintf(minute, "%02d", ltm->tm_min);
	sprintf(second, "%02d", ltm->tm_sec);
	char data_str[18];
	sprintf(data_str, "%s/%s/%s %s:%s:%s", year, month, day, hour, minute, second);
	STRING time_str(data_str);
	return time_str;
}

int fileLock(const char* file_name){
	FILE_LOCK lock;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	lock.l_type = F_WRLCK;
	int fd = open(file_name, O_RDWR | O_CREAT | O_EXCL);
	if (fd >= 0){
		int l_st = fcntl(fd, F_SETLK, &lock);
		if (l_st < 0){
			return -1;
		}
	}

	return fd;
}

int fileUnlock(int fd){
	FILE_LOCK lock;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	lock.l_type = F_UNLCK;
	int l_st = fcntl(fd, F_SETLK, &lock);
	if (l_st < 0){
		return -1;
	}
	close(fd);
	return fd;
}
